<template>
  <div class="activityPost">
    <top-bar :isBlack="true" title="推广申请"></top-bar>
    <p class="title">填写申请信息</p>
    <div class="input-item">
      <input
        type="text"
        class="input"
        v-model="title"
        placeholder="请输入推广标题"
      />
    </div>
    <div class="input-item">
      <input
        type="text"
        class="input"
        v-model="hotel"
        placeholder="请输入推广酒店，例：天津海河英迪格酒店"
      />
    </div>
    <div class="input-item" @click="startShow = true">
      <p class="input" v-if="time.length == 2">{{ time[0] }} - {{ time[1] }}</p>
      <p class="input" v-else>请输入推广时间段</p>
      <img src="@/assets/icon_06.png" alt="" class="icon" />
    </div>
    <p class="title">上传活动图片</p>
    <p class="tips">建议上传图片大小:1920px*1080px</p>
    <div class="uploader-wrapper">
      <van-uploader :max-count="1" :after-read="afterRead">
        <img v-if="image" :src="image" alt="" class="uploader-img" />
        <img v-else src="@/assets/icon_13.png" alt="" class="uploader-img" />
      </van-uploader>
    </div>
    <div class="btn-wrapper" v-show="btnShow">
      <van-button color="#224448" block @click="save">保存</van-button>
    </div>
    <van-popup v-model="startShow" position="bottom">
      <van-datetime-picker
        v-model="startDate"
        type="datetime"
        title="选择开始时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="startConfirm"
        @cancel="startCancel"
      />
    </van-popup>
    <van-popup v-model="endShow" position="bottom">
      <van-datetime-picker
        v-model="endDate"
        type="datetime"
        title="选择结束时间"
        :min-date="minEndDate"
        :max-date="maxDate"
        @confirm="endConfirm"
        @cancel="endCancel"
      />
    </van-popup>
  </div>
</template>

<script>
import moment from "moment";
moment.locale("zh-cn");
import { Dialog, Toast } from "vant";
import TopBar from "@/components/topBar.vue";
export default {
  name: "activityPost",
  data() {
    return {
      title: "",
      hotel: "",
      minDate: new Date(2020, 0, 1),
      minEndDate: new Date(2020, 0, 1),
      maxDate: new Date(2045, 10, 1),
      startDate: new Date(),
      endDate: new Date(),
      startShow: false,
      endShow: false,
      image: "",
      time: [],
      docmHeight: document.documentElement.clientHeight, //默认屏幕高度
      showHeight: document.documentElement.clientHeight, //实时屏幕高度
      btnShow: true,
    };
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.showHeight = document.documentElement.clientHeight;
      })();
    };
  },
  methods: {
    startConfirm(val) {
      this.time[0] = moment(val).format("YYYY-MM-DD HH:mm");
      this.minEndDate = val;
      this.startShow = false;
      this.endShow = true;
    },
    startCancel() {
      this.startShow = false;
    },
    endConfirm(val) {
      this.time[1] = moment(val).format("YYYY-MM-DD HH:mm");
      this.endShow = false;
    },
    endCancel() {
      this.endShow = false;
    },
    afterRead(file) {
      Toast.loading({
        message: "上传中...",
        forbidClick: true,
        duration: 0,
      });
      let quality = 1;
      let _this = this;
      let imgFile = file.file;
      if (imgFile.size > 500 * 1024) {
        quality = (500 * 1024) / file.size;
      }
      let img = new Image();
      img.src = file.content;
      img.onload = function () {
        let base64Img = _this.rotateImage(this, quality);
        let endFile = _this.dataURLtoFile(
          base64Img,
          imgFile.name.split(".")[0]
        );
        let formData = new FormData();
        formData.append("file", endFile);
        _this.$api
          .upload(formData)
          .then((res) => {
            Toast.clear();
            if (res.status_code == 200) {
              // console.log(res);
              _this.image = res.data;
            } else {
              Toast(res.message ? res.message : "上传错误");
            }
          })
          .catch((e) => {
            Toast.clear();
            Toast("上传错误");
          });
      };
    },
    save() {
      if (!this.title) {
        Dialog({ message: "请先输入活动标题" });
        return;
      }
      if (!this.hotel) {
        Dialog({ message: "请先输入活动酒店" });
        return;
      }
      if (this.time.length != 2) {
        Dialog({ message: "请先选择活动时间" });
        return;
      }
      if (!this.image) {
        Dialog({ message: "请先上传活动图片" });
        return;
      }
      Toast.loading({
        message: "保存中...",
        forbidClick: true,
        duration: 0,
      });
      this.$api
        .activityStore({
          title: this.title,
          image: this.image,
          hotel: this.hotel,
          start_time: this.time[0],
          end_time: this.time[1],
        })
        .then((res) => {
          this.desc = "";
          this.type = {};
          Toast.clear();
          if (res.status_code == 200) {
            Dialog({ message: "保存成功" }).then(() => {
              this.$router.go(-1);
            });
          } else {
            Dialog({ message: res.message });
          }
        });
      // this.$router.go(-1);
    },
    //旋转图片
    rotateImage(image, quality) {
      let _this = this;
      let width = image.width;
      let height = image.height;

      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      let newImage = new Image();
      let imageDate;

      _this.Exif.getData(image, function () {
        //  _this.Exif.getAllTags(this);
        var orientation = _this.Exif.getTag(this, "Orientation");
        console.log(orientation);
        let userAgent = navigator.userAgent.toLowerCase();
        let ios = userAgent.match(/cpu iphone os (.*?) like mac os/);
        let reg = /.*\..*/; //判断是否有小数点
        if (!ios) {
          canvas.height = height;
          canvas.width = width;
          ctx.drawImage(image, 0, 0);
          imageDate = canvas.toDataURL("Image/jpeg", quality);
          newImage.src = imageDate;
        } else {
          let iosVersion = ios[1].replace(/_/g, "."); //获取ios系统版本
          if (Number(iosVersion.split(".")[0]) < 13) {
            switch (orientation) {
              case 6:
                console.log("旋转90°");
                canvas.height = width;
                canvas.width = height;
                ctx.rotate(Math.PI / 2);

                ctx.drawImage(image, 0, -height);
                imageDate = canvas.toDataURL("Image/jpeg", quality);
                newImage.src = imageDate;
                break;
              case 3:
                console.log("旋转180°");
                canvas.height = height;
                canvas.width = width;
                ctx.rotate(Math.PI);

                ctx.drawImage(image, -width, -height);
                imageDate = canvas.toDataURL("Image/jpeg", quality);
                newImage.src = imageDate;
                break;
              case 8:
                console.log("旋转270°");
                canvas.height = width;
                canvas.width = height;
                ctx.rotate(-Math.PI / 2);

                ctx.drawImage(image, -height, 0);
                imageDate = canvas.toDataURL("Image/jpeg", quality);
                newImage.src = imageDate;
                break;
              default:
                console.log("不旋转");
                canvas.height = height;
                canvas.width = width;
                ctx.drawImage(image, 0, 0);
                imageDate = canvas.toDataURL("Image/jpeg", quality);
                newImage.src = imageDate;
                break;
            }
          } else if (Number(iosVersion.split(".")[0]) > 13) {
            //正常
            canvas.height = height;
            canvas.width = width;
            ctx.drawImage(image, 0, 0);
            imageDate = canvas.toDataURL("Image/jpeg", quality);
            newImage.src = imageDate;
          } else {
            //等于13 判断ios系统有无.
            if (reg.test(iosVersion)) {
              if (Number(iosVersion.split(".")[1]) < 4) {
                //需要调整旋转
                switch (orientation) {
                  case 6:
                    console.log("旋转90°");
                    canvas.height = width;
                    canvas.width = height;
                    ctx.rotate(Math.PI / 2);

                    ctx.drawImage(image, 0, -height);
                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                    newImage.src = imageDate;
                    break;
                  case 3:
                    console.log("旋转180°");
                    canvas.height = height;
                    canvas.width = width;
                    ctx.rotate(Math.PI);

                    ctx.drawImage(image, -width, -height);
                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                    newImage.src = imageDate;
                    break;
                  case 8:
                    console.log("旋转270°");
                    canvas.height = width;
                    canvas.width = height;
                    ctx.rotate(-Math.PI / 2);

                    ctx.drawImage(image, -height, 0);
                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                    newImage.src = imageDate;
                    break;
                  default:
                    console.log("旋转90°2");
                    canvas.height = height;
                    canvas.width = width;
                    ctx.drawImage(image, 0, 0);
                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                    newImage.src = imageDate;
                    break;
                }
              } else {
                canvas.height = height;
                canvas.width = width;
                ctx.drawImage(image, 0, 0);
                imageDate = canvas.toDataURL("Image/jpeg", quality);
                newImage.src = imageDate;
              }
            } else {
              switch (orientation) {
                case 6:
                  console.log("旋转90°");
                  canvas.height = width;
                  canvas.width = height;
                  ctx.rotate(Math.PI / 2);

                  ctx.drawImage(image, 0, -height);
                  imageDate = canvas.toDataURL("Image/jpeg", quality);
                  newImage.src = imageDate;
                  break;
                case 3:
                  console.log("旋转180°");
                  canvas.height = height;
                  canvas.width = width;
                  ctx.rotate(Math.PI);

                  ctx.drawImage(image, -width, -height);
                  imageDate = canvas.toDataURL("Image/jpeg", quality);
                  newImage.src = imageDate;
                  break;
                case 8:
                  console.log("旋转270°");
                  canvas.height = width;
                  canvas.width = height;
                  ctx.rotate(-Math.PI / 2);

                  ctx.drawImage(image, -height, 0);
                  imageDate = canvas.toDataURL("Image/jpeg", quality);
                  newImage.src = imageDate;
                  break;
                default:
                  console.log("不旋转");
                  canvas.height = height;
                  canvas.width = width;
                  ctx.drawImage(image, 0, 0);
                  imageDate = canvas.toDataURL("Image/jpeg", quality);
                  newImage.src = imageDate;
                  break;
              }
            }
          }
        }
      });
      return imageDate;
    },
    //将base64转换为文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }

      return new File([u8arr], filename, {
        type: mime,
      });
    },
  },
  watch: {
    showHeight() {
      if (this.docmHeight > this.showHeight) {
        this.btnShow = false;
      } else {
        this.btnShow = true;
      }
    },
  },
  components: {
    TopBar,
  },
};
</script>

<style lang="scss">
.activityPost {
  .van-button {
    height: 54px;
  }
  .van-button--normal {
    font-size: 16px;
  }
}
</style>
<style lang="scss" scoped>
.activityPost {
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9;
  background-color: #fff;
  overflow-y: auto;
  padding-bottom: 56px;
  .title {
    line-height: 40px;
    background: #224448;
    padding: 0 15px;
    font-size: 13px;
    color: #ffffff;
  }

  .input-item {
    margin: 20px 15px;
    height: 40px;
    background: #f4f4f4;
    border-radius: 10px;
    line-height: 40px;
    padding: 0 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .input {
      flex: 1;
      font-size: 14px;
      height: 100%;
      background-color: transparent;
      color: #919191;
      &::placeholder {
        font-size: 14px;
        color: #919191;
      }
    }
    .icon {
      width: 13px;
      height: 11px;
      object-fit: contain;
    }
  }

  .tips {
    font-size: 13px;
    font-weight: 500;
    color: #919191;
    margin: 15px;
  }

  .uploader-wrapper {
    padding-left: 15px;
    .uploader-img {
      width: 88px;
      height: 78px;
      object-fit: contain;
    }
  }
  .btn-wrapper {
    position: fixed;
    left: 0;
    bottom: 0;
    right: 0;
  }
}
</style>